package timing.ukulele.storage.config;

import io.minio.MinioAsyncClient;
import io.minio.MinioClient;
import okhttp3.HttpUrl;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import timing.ukulele.storage.minio.StorageClientFactory;

import java.net.URL;

@Configuration
@EnableConfigurationProperties(StorageClientProperties.class)
public class StorageClientAutoConfiguration {
    private final StorageClientProperties properties;

    public StorageClientAutoConfiguration(StorageClientProperties storageClientProperties) {
        this.properties = storageClientProperties;
    }

    @Bean
    MinioClient minioClient() throws Exception {
        URL url = null;
        if (properties.getUrlString() != null && properties.getUrlString().length() > 0) {
            url = new URL(properties.getUrlString());
        }
        HttpUrl httpUrl = null;
        if (properties.getHttpUrlString() != null && properties.getHttpUrlString().length() > 0) {
            httpUrl = HttpUrl.parse(properties.getHttpUrlString());
        }
        return StorageClientFactory.INSTANCE.createStorageClient(properties.getEndpoint(),
                properties.getPort(),
                properties.getAccessKey(),
                properties.getSecretKey(),
                properties.getSecure(),
                url, httpUrl);
    }

    @Bean
    MinioAsyncClient minioAsyncClient() {
        return MinioAsyncClient.builder()
                .endpoint("http://" + properties.getEndpoint() + ":" + properties.getPort())
                .credentials(properties.getAccessKey(), properties.getSecretKey())
                .build();
    }
}
